﻿using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.XtraEditors;
using EasyXaf.ExcelImporters;
using System.IO;
using ListView = DevExpress.ExpressApp.ListView;

namespace EasyXaf.Win.ExcelImporters;

public class WinImportExcelController : ViewController<ListView>
{
    private ImportExcelController _importExcelController;

    protected override void OnActivated()
    {
        base.OnActivated();

        var importExcelController = Frame.GetController<ImportExcelController>();
        if (importExcelController != null && importExcelController.Active)
        {
            _importExcelController = importExcelController;
            importExcelController.ImportAction.Execute += ImportAction_Execute;
        }
    }

    protected override void OnDeactivated()
    {
        if (_importExcelController != null)
        {
            _importExcelController.ImportAction.Execute -= ImportAction_Execute;
        }

        base.OnDeactivated();
    }

    private void ImportExcel(IModelImporting importingModel)
    {
        var openFileDialog = new OpenFileDialog
        {
            Filter = "Excel(*.xlsx)|*.xlsx"
        };

        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            var excelImporter = new ExcelImporter(View, Application, importingModel);
            using var fileStream = new FileStream(openFileDialog.FileName, FileMode.Open);
            try
            {
                if (excelImporter.ImportExcel(fileStream))
                {
                    View.RefreshDataSource();
                    Application.ShowViewStrategy.ShowMessage("导入Excel成功", InformationType.Info);
                }
                else
                {
                    XtraMessageBox.Show("导入Excel失败，详细请查看Excel文件", "导入Excel", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"导入Excel失败，{ex.Message}", "导入Excel", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    private void ExportExcelTemplate(IModelImporting importingModel)
    {
        var importExcelTemplate = new ImportExcelTemplate(View, Application, importingModel);

        var saveFileDialog = new SaveFileDialog
        {
            Filter = "Excel(*.xlsx)|*.xlsx"
        };

        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            try
            {
                using var fileStream = new FileStream(saveFileDialog.FileName, FileMode.Create);
                using var templateStream = importExcelTemplate.GenerateTemplate();
                templateStream.Seek(0, SeekOrigin.Begin);
                var buffer = new byte[1024];
                while (templateStream.Read(buffer, 0, buffer.Length) > 0)
                {
                    fileStream.Write(buffer, 0, buffer.Length);
                }
                Application.ShowViewStrategy.ShowMessage("导出Excel模板成功", InformationType.Info);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"导出Excel模板失败，{ex.Message}", "Excel模板", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }

    private void ImportAction_Execute(object sender, SingleChoiceActionExecuteEventArgs e)
    {
        if (e.SelectedChoiceActionItem?.Id?.ToString() == "ImportExcel")
        {
            if (e.SelectedChoiceActionItem.Data is IModelImporting importingModel)
            {
                ImportExcel(importingModel);
            }
        }
        else if (e.SelectedChoiceActionItem?.Id?.ToString() == "ExcelTemplate")
        {
            if (e.SelectedChoiceActionItem.Data is IModelImporting importingModel)
            {
                ExportExcelTemplate(importingModel);
            }
        }
    }
}
